#include "Common.hpp"
#include "Socket.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace SocketModule;
using namespace LogModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket>& sock, InetAddr& client)>;

class TcpServer{
public:
    TcpServer(uint16_t port, ioservice_t func)
        : _port(port), _service(func), _isrunning(false), _listensockotr(std::make_unique<TcpSocket>()) 
    {
        _listensockotr->BuildTcpSocketMethod(_port);
    }

    void Start(){
        _isrunning = true;
        while(_isrunning){
            InetAddr client;
            auto sock = _listensockotr->Accept(&client);
            if(sock == nullptr){
                continue;
            }
            LOG(LogLevel::DEBUG) << "accept success: " << client.StringAddr();
            
            pid_t id = fork();
            if(id < 0){
                LOG(LogLevel::FATAL) << "fork error";
                exit(FORK_ERR);
            }
            else if(id == 0){
                _listensockotr->Close();
                if(fork() > 0)
                    exit(OK);
                
                _service(sock, client);
                sock->Close();
                exit(OK);
            }
            else{
                sock->Close();
                pid_t rid = waitpid(id, nullptr, 0);
                (void)rid;
            }
        }
        _isrunning = false;
    }

    
private:
    uint16_t _port;
    bool _isrunning;
    std::unique_ptr<Socket> _listensockotr;
    ioservice_t _service;
};